<template>
  <!-- v-model:file-list="fileList" -->
  <el-form ref="formRef" :rules="rules" :model="additionalParamForm" style="margin-right: 0!important">
    <el-form-item :label="props.modelValue.pageConfig.additionalParamLabel ?? '类型选择'"
      :prop="props.modelValue.pageConfig.additionalParamKey" v-if="props.modelValue.pageConfig.additionalParamOptions">
      <SingleLayerSelect v-model="additionalParamForm[props.modelValue.pageConfig.additionalParamKey]"
        :options="props.modelValue.pageConfig.additionalParamOptions" />
    </el-form-item>
    <el-upload style="width: 100%;margin-top: 20px;" drag :multiple="false" :auto-upload="false"
      :disabled="uploadDisabled"
      :on-change="handleChange"
      accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        <template v-if="!uploadDisabled">
        拖拽或者 <em>点击上传</em>
        </template>
        <template v-else>
          当前无可用模板，请先配置模板后，基于模板填写后点击或拖拽上传
        </template>
      </div>
      <template #tip>
        <el-row style="margin-top: 20px;" align="middle">
          <el-col :span="20">
            <div class="upload-tips">{{ uploadTips }}</div>
          </el-col>
          <el-col :span="4" style="display: flex;justify-content: flex-end;"
            v-if="props.modelValue.pageConfig.templateType && !uploadDisabled">
            <el-button type="primary" @click="handleTemplateDownload">下载模板</el-button>
          </el-col>
        </el-row>
      </template>

      <template #file="{ file, index }">
        <!-- <div style="display: flex;" @click="(e)=>handlePreview(file)">
          <span class="fie-name" style="flex:1 0;margin-left:20px">
            {{ file.name || props.modelValue }} 
          </span>
          <FilePreview v-model="file.url"/>
        </div> -->
      </template>
    </el-upload>
  </el-form>
  <div class="horizontal-scroll-container">
    <el-dialog v-model="showConfirmDialog" title="导入信息确认">
      <InfoConfirm v-model="excelData" />
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>

  <el-dialog v-model="showPreviewDialog">
    <div id="preview" ref="preview"></div>
  </el-dialog>
</template>

<script setup lang="ts">
import { FormRules, UploadFile, UploadFiles } from "element-plus";
import CompanyInfoInstitutionalTemplateApi from "../api/webPath/CompanyInfoInstitutionalTemplateApi";
import CommonApi from "../api/CommonApi";

interface Props {
  modelValue: {
    pageConfig: {
      additionalSaveParams: Record<any, any>,
      // attachmentType: "excel" | "word";
      templateType?: string,
      paramMessage: string,
      additionalParamKey: string,
      additionalParamLabel?: string,
      additionalParamOptions: {
        value: any,
        label: any
      }[]
      doUpload: (data: any) => Promise<any>;
      doBatchSave: (data: any) => Promise<any>;
    };
  };
}
const tips = ref()
let templateUrl = ref("")
let templateName = ""
const props = defineProps<Props>();
const rules = reactive<FormRules>({
  [props.modelValue.pageConfig.additionalParamKey]: {
    required: true,
    message: props.modelValue.pageConfig.paramMessage
  }

})
const formRef = useTemplateRef("formRef")
const additionalParamForm = ref<Record<string, any>>({

})

// const fileList = computed<UploadUserFile[]>(()=>{
// })
onMounted(async () => {
  console.log("modelValue", props.modelValue);
  const { data: { records: templateList } } = await CompanyInfoInstitutionalTemplateApi.getPageData({ templateType: props.modelValue.pageConfig.templateType })
  templateUrl.value = templateList && templateList.length > 0 && templateList[0].templateUrl
  templateName = templateList && templateList.length > 0 && templateList[0].templateName
  tips.value = templateList && templateList.length > 0 && templateList[0].templateDescribe
});

const uploadDisabled = computed(() => {
  if (props.modelValue.pageConfig.templateType && (!templateUrl.value || templateUrl.value === "" )){
    return true
  } else {
    return false
  }
})

const uploadTips = computed(() => {
  if (tips.value) {
    return tips.value 
  } else {
    if (uploadDisabled) {
      return "暂无附件模板"
    } else {
      return "请上传需要导入的附件文件"
    }
  }
})

const emit = defineEmits(["update:modelValue", "callBack"]);
const preview = useTemplateRef("preview");
const showConfirmDialog = ref(false);
const showPreviewDialog = ref(false);
const excelData = ref({
  mainTitle: "供应商基本信息库",
  subTitle: [
    {
      subtitle: "营业执照信息",
      fields: {
        name: "企业名称*",
        address: "企业地址",
        uniqueId: "统一社会信用代码*",
        releaseDate: "发证日期",
      },
    },
    {
      subtitle: "经营许可证信息",
      fields: {
        businiessLicenseId: "许可证编号",
        applyReleaseDate: "发证日期",
        avaliableDate: "有效日期",
        bussinessDomain: "经营项目",
      },
    },
    {
      subtitle: "生产许可证信息",
      fields: {
        produceLicenseId: "许可证编号",
        produceLicneseReleaseDate: "发证日期",
        produceLicenseAvaliableDate: "有效日期",
        produceLicenseBussinessDomain: "经营项目",
        produceCategory: "产品类别",
        categoryId: "类别编号",
        categoryName: "类别名称",
        categoryDetail: "品种明细",
      },
    },
  ],
  records: [
    {
      name: "中粮东海粮油工业（张家港）有限公司",
      address: "测试地址",
      uniqueId: "913205926082583175",
      releaseDate: "2019/12/9",
      businiessLicenseId: "SC10132058200031",
      applyReleaseDate: "",
      avaliableDate: "",
      bussinessDomain: "",
      produceLicenseId: "",
      produceLicneseReleaseDate: "",
      produceLicenseAvaliableDate: "",
      produceLicenseBussinessDomain: "",
      produceCategory: "",
      categoryId: "",
      categoryName: "",
      categoryDetail: "",
    },
  ],
});


// 模板下载
async function handleTemplateDownload() {
  console.log("template download data ", "templateName: ", templateName, " templateUrl: ", templateUrl.value)
  CommonApi.downloadAttachment(templateUrl.value, templateName)
}

function handleChange(file: UploadFile, files: UploadFiles) {
  const form = new FormData();
  console.log("handle change");
  formRef.value?.validate((validate) => {
    console.log("validate", validate)
    if (file.raw && validate) {
      const loading = $baseLoading("上传中，请耐心等待");
      if (files)
        try {
          if (Object.keys(additionalParamForm.value).length !== 0) {
            const key = props.modelValue.pageConfig.additionalParamKey
            form.append(key, additionalParamForm.value[key])
          }
          form.append("file", file.raw);
          console.log("props.pagConfig.doupload", props.modelValue.pageConfig);
          props.modelValue.pageConfig.doUpload(form).then((res) => {
            if (res) {
              const { data } = res
              console.log("attachmentType", "excel");
              // if (props.attachmentType === "excel") {
              console.log("data:", data);
              // console.log("typeof data",typeof data)
              if (typeof data === "object") {
                excelData.value = data;
              } else {
                excelData.value = JSON.parse(data);
              }
              // console.log("records:",JSON.parse(excelData.value.records))
              console.log("excelData:", excelData.value);
              showConfirmDialog.value = true;
              // }else{
              //   emit("update:modelValue",data)
              // }
              loading.close();
              file.status = "success";
            } else {
              loading.close();
              file.status = "fail";
            }
          });
        } catch (e) {
          console.log("error", e);
          loading.close();
        }
    } else {
      files.splice(0, 1)
    }
  })
}

/**
 * 信息确认弹窗点击取消
 */
function handleCancel() {
  showConfirmDialog.value = false;
  emit("callBack", "cancel")
}
/**
 * 信息确认后处理
 */
async function handleConfirm() {
  try {
    let data;
    console.log("pageconfig", props.modelValue.pageConfig)
    console.log("saveparam", props.modelValue.pageConfig.additionalSaveParams)
    if (props.modelValue.pageConfig.additionalSaveParams) {
      console.log("have save param")
      data = JSON.stringify({
        ...props.modelValue.pageConfig.additionalSaveParams,
        list: excelData.value.records,
      });
    } else {
      console.log("don't have save param")
      if (additionalParamForm.value) {
        data = JSON.stringify({ ...additionalParamForm.value, list: excelData.value.records });
      } else {

        data = JSON.stringify({ list: excelData.value.records });
      }
    }
    const res = await props.modelValue.pageConfig.doBatchSave(data);
    if (res) {
      console.log("返回结果", res);
      $baseMessage("保存成功", "success");
      emit("callBack", "success");
    }
  } catch (e) {
    console.log("保存错误：", e);
    $baseMessage("保存失败", "error");

    emit("callBack", "fail");
  } finally {
    showConfirmDialog.value = false;
  }
}

/**
 * 附件预览
 */
function handlePreview(file: File) {
  console.log(file);
  console.log("preivevw", preview.value);
  // renderAsync(file,preview.value).then(v=>{
  //   console.log(v)
  // })
  // showPreviewDialog.value = true
}
</script>

<style scoped>
.horizontal-scroll-container {
  overflow-x: auto;
  /* 强制显示横向滚动条 */
  width: 100%;
  min-height: 100%;
  white-space: nowrap;
  /* 防止内容换行 */
}

.el-form {
  /* min-width: 1200px; */
  /* 确保内容宽度大于容器 */
  display: inline-block;
  width: 100%;
}

.upload-tips {
  font-size: 14px;
  color: red;
}
</style>
